<?php

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;


function admin_user()
{
    return Auth::guard('admin');
}

function buildTree($items, $parentId = null, $mk='id', $pk='parent_id', $call=null) {
    $branch = [];

    if( is_null($call) ){
    	$call = function($item){
    		return $item;
    	};
    }

    foreach ($items as $item) {
        // 检查当前项的parent_id是否与传入的parentId匹配
        if ($item[$pk] == $parentId) {
            // 递归构建子树
            // dd(Arr::get($item, 'id'));
            $pid = Arr::get($item, $mk);
            $children = buildTree($items, $pid, $mk, $pk, $call);
            if (!empty($children)) {
                $item['children'] = $children;
            }
            $branch[] = $call($item);
        }
    }

    return $branch;
}

/**
 * 获得后台控制器路由别名
 * 如果未设置 会自动生成列入 admin.system.role.store
 */
function getRouteNameFromRouteObject(\Illuminate\Routing\Route $route)
{
    // if( $route->getName() ){
    //     return $route->getName();
    // }

    $namespace = Arr::get($route->action, 'namespace');

    $controllerClassName = Route::current()->getControllerClass();
    $methodName = $route->getActionMethod();

    if( $controllerClassName==$methodName ){
        $methodName = '__invoke';
    }

    // 控制器类名相对控制器目录的名称
    $relativeControllerName = substr($controllerClassName, strlen($namespace));
    $baseControllerName = substr($relativeControllerName, 0, strlen($relativeControllerName)-10);// 假设控制器类名以'Controller'结尾

    // 用点分割目录 且小写 
    $dotLowerCase = str_replace('\\', '.', strtolower($baseControllerName));

    // 根据控制器的命名空间确定路由名称的前缀
    $prefix = str_starts_with($controllerClassName, 'Destroyer\Http\Controllers') ? 'system' : 'admin' ;

    return sprintf('%s%s.%s', $prefix, $dotLowerCase, $methodName);
}